/*
 * @Date         : 2024-05-17 15:29:15 星期5
 * @Author       : xut
 * @Description  :
 */
import { User } from "@prisma/client"
import { findUniqueUser } from "../services/user.service"
import { redisClient } from "../utils/connectRedis"
import { verifyJwt } from "../utils/jwt"

export async function deserializeUser(
  access_token: string
): Promise<User | null> {
  try {
    if (!access_token) return null

    const decoded = await verifyJwt<{ sub: string }>(
      access_token,
      "accessTokenPublicKey"
    )

    if (!decoded) return null

    const session = await redisClient.get(decoded.sub)

    if (!session) return null

    const user = await findUniqueUser({ id: JSON.parse(session).id })

    if (!user) return null

    return user
  } catch {
    return null
  }
}
